/*
 * @Author: along
 * @Date: 2020-06-20 09:05
 * @Last Modified by: along
 * @Last Modified time: 20120-06-20 09:30
 */

import axios from 'axios';
import Qs from 'qs';

var sessionTicket = '';

const server = axios.create({
    // http://nadmin-api.wxhand.com/admin/Phaadmin/client/student/course_cate%5Cget_list
    baseURL: 'http://nadmin-api.wxhand.com/admin/Phaadmin/',//请求服务器的url,这里可以设置环境变量设置测试和线上的url
    // timeout: 2000,//请求超时
    method: 'post',//请求方法，默认get
    withCredentials: false, // 默认的，表示跨域请求是否使用凭证
    transformRequest: [function (data) {//只能用在PUT，GET，POST上，向服务器发送数据前修改请求数据
        let resData = data;

        if(!(resData instanceof FormData)) {
            resData = Qs.stringify(resData);
        }
        return resData;
    }]
});

/**
 * 获取token
 */
function getSessionTicket (callback) {

    server.post('/client/__local/basic%5Ccreate_session_ticket',{}).then(resp => {
        if(resp.status !== 200) {
            return Promise.reject(resp);
        }

        let response = resp.data;

        if(response.code == 1) {
            sessionTicket = response.data.session_ticket;
            localStorage.setItem('sessionTicket', response.data.session_ticket);
        }

        callback(response.data.session_ticket);
    }).catch(error => {
        return Promise.reject(error);
    });
}


//设置axios的全局默认值
// axios.defaults.baseURL = '';
// axios.defaults.headers.common['token'] = 'test';
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//添加请求拦截器
server.interceptors.request.use(function(config) {
    //发送请求之前做些什么
    config.headers['zsdx-session-ticket'] = sessionTicket;

    return config;
}, function (error) {
    return Promise.reject(error);
});

//添加响应拦截器
server.interceptors.response.use(function(response) {
    //对响应数据做点什么
    return response;
}, function (error) {
    return Promise.reject(error);
});


/**
 * 处理请求返回结果
 */
function dealResponse (resp, options) {
    if (resp.status != '200') {
        return Promise.reject(resp);
    }

    let instance = options.instance;

    if(resp.data.code == 1001) { //sessionTicket缺失或者失效
        if(!sessionTicket) {
            setTimeout(function () {
                instance.$post(options.url, options.data, options.success, options.fail);
            }, 200);
        }
        return;
    }

    if(resp.data.code == 1002) {
        instance.$post('http://nadmin-api.wxhand.com/admin/Phaadmin/client/__local/user%5Clogin', {
            username: 'yangwenlong',
            password: 'yangwenlong'
        },resp => {
            console.log(resp, '登录成功');
        });
        return;
    }

    if(options.success) {
        options.success(resp.data);
        return;
    }
    return;

}

/**
 * post请求
 * @param {*} Vue
 * @param {*} options
 */
function post (url, data, success, fail, session_ticket) {
    let instance = this;

    let str = session_ticket;

    if(!str) {
        getSessionTicket(function(currTicket) {
            instance.$post(url, data, success, fail, currTicket);
        });
    } else {
        server.post(url,data).then(function(resp) {
            dealResponse(resp, {
                instance,
                url,
                data,
                success,
                fail
            });
        });
    }
}


function install(Vue, options) {
    Vue.axios = axios;

    Object.defineProperties(Vue.prototype, {
        $post: {
            get() {
                return post.bind(this);
            }
        },
        axios: {
            get() {
                return axios;
            }
        },
    });
}

export default install;